from sqlalchemy.orm import Session
from app.models.resource import Resource
from app.schemas.resource import ResourceCreate, ResourceUpdate
from typing import List, Optional

# 获取资源通过ID
def get_resource(db: Session, resource_id: int):
    return db.query(Resource).filter(Resource.id == resource_id).first()

# 获取资源列表
def get_resources(db: Session, skip: int = 0, limit: int = 100, type: Optional[str] = None, related_case_id: Optional[int] = None):
    query = db.query(Resource)
    if type:
        query = query.filter(Resource.type == type)
    if related_case_id:
        query = query.filter(Resource.related_case_id == related_case_id)
    return query.offset(skip).limit(limit).all()

# 创建资源
def create_resource(db: Session, resource: ResourceCreate):
    db_resource = Resource(
        name=resource.name,
        type=resource.type,
        path=resource.path,
        version=resource.version,
        description=resource.description,
        related_case_id=resource.related_case_id
    )
    db.add(db_resource)
    db.commit()
    db.refresh(db_resource)
    return db_resource

# 更新资源
def update_resource(db: Session, resource_id: int, resource: ResourceUpdate):
    db_resource = db.query(Resource).filter(Resource.id == resource_id).first()
    if db_resource:
        if resource.name is not None:
            db_resource.name = resource.name
        if resource.type is not None:
            db_resource.type = resource.type
        if resource.path is not None:
            db_resource.path = resource.path
        if resource.version is not None:
            db_resource.version = resource.version
        if resource.description is not None:
            db_resource.description = resource.description
        if resource.related_case_id is not None:
            db_resource.related_case_id = resource.related_case_id
        db.commit()
        db.refresh(db_resource)
    return db_resource

# 删除资源
def delete_resource(db: Session, resource_id: int):
    db_resource = db.query(Resource).filter(Resource.id == resource_id).first()
    if db_resource:
        db.delete(db_resource)
        db.commit()
    return db_resource